package com.cuit.jifver.weibo.db;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;

import com.cuit.jifver.weibo.utils.LogUtil;

/**
 * class SQLliteDatabase
 **/

public class DBHelper extends SQLiteOpenHelper {
	
	//public static final String TAG = "SQLiteOpenHelper";
	
	private static final String DATABASE_NAME = "db_weibo.db";
	private static final String TABLE_USER = "t_user";
	private static final int DATABASE_VERSION = 1;
	private SQLiteDatabase m_db;
	/*************************************************************************
	 * PUBLIC FILED_ID
	 *************************************************************************/
	private final String FIELD_ID = "id";
	
	/*************************************************************************
	 * TABLE_USER
	 *************************************************************************/
	
	
	public static final String USER_ID 		   				= "uid";
	public static final String USER_NAME 		    		= "name";
	public static final String USER_ACCESS_TOKEN  			= "token";
	public static final String USER_ACCESS_TOKEN_SECRET 	= "secret";
	public static final String USER_TYPE 	                = "type";
//	public static final String FIELD_PRODUCT_SKU 		= "Sku";

	
//	public static final String FIELD_PRODUCT_SKU 		= "Sku";
//	public static final String FIELD_PRODUCT_NAME 		= "ProductName";
//	public static final String FIELD_IMAGE_LOCAL	 	= "ImageData";
//	public static final String FIELD_IMAGE_URL_HTTP 	="ServerImagePath";
//	public static final String FIELD_PRICE_RETIAL	 	= "RetailPrice";
//	public static final String FIELD_ECOUPON_DESC		= "EcouponDesc";
//	public static final String FIELD_ECOUPON_ACTIVE		= "EcouponActive";
//	public static final String FIELD_ECOUPON_CODE		= "ECouponCode";
//	public static final String FIELD_ECOUPON_USED 		= "EcouponHadUsed";
//	public static final String FIELD_ECOUPON_AMOUNT 	= "EcouponAmount";
//	public static final String FIELD_DETAIL_TITLE 		= "EcouponOfferDetailTitle";
//	public static final String FIELD_DETAIL_SUB_TITLE	= "EcouponOfferDetailSubTitle";
//	public static final String FIELD_DETAIL_DESC 		= "EcouponOfferDetailDescription";
//	public static final String FIELD_END_DATE			= "EndDate";
//	public static final String FIELD_PERSONAL	 		= "HasPersonalization";
//	public static final String FIELD_CATELOG_ID = "CatalogId";
	
	public static final int RET_OK = 0;
	public static final int RET_ERROR = -1;
	public static final int RET_RECORD_EXIST = -100;
	public static final int RET_INVALID_PARAMETER = -101;
	
	

	public DBHelper(Context context) {
		super(context, DATABASE_NAME, null, DATABASE_VERSION);
		try{
			m_db = getWritableDatabase();
			LogUtil.d(this, "DBHelper()");
		}catch(SQLiteException e){
			LogUtil.d(this, e.toString());
		}
	}
	
	@Override
	public void close(){
		if (m_db != null){
			m_db.close();
			m_db = null;
		}
		super.close();
	}
	
	private void createTable_Product(boolean isDeleteIfExist,SQLiteDatabase db){
		LogUtil.i(this, "create table");
		if (isDeleteIfExist)
			db.execSQL("DROP TABLE IF EXISTS " + TABLE_USER);

		db.execSQL("CREATE TABLE " + TABLE_USER + " (" + FIELD_ID + " INTEGER PRIMARY KEY," + USER_ID + " TEXT,"+ USER_NAME + " TEXT," + USER_ACCESS_TOKEN + " TEXT," + USER_ACCESS_TOKEN_SECRET + " TEXT" + ");");
		// sina_home db.execSQL("CREATE TABLE IF NOT EXISTS home_table (mblogid TEXT, gid TEXT, gsid TEXT, uid TEXT, favid TEXT, nick TEXT, remark TEXT, portrait TEXT, vip INTEGER, content TEXT, rtrootuid TEXT, rtrootnick TEXT, rtrootvip TEXT, rtreason TEXT, rtnum INTEGER, commentnum INTEGER, time TEXT, pic TEXT, src TEXT,rtrootid TEXT,longitude TEXT,latitude TEXT)");
	}
	

	@Override
	public void onCreate(SQLiteDatabase db) {
		createTable_Product(false,db);
	}

	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
		int version = oldVersion;

		if (version != DATABASE_VERSION) {
			//db.execSQL("DROP TABLE IF EXISTS " + TABLE_PRODUCT);
			//onCreate(db);
			createTable_Product(true,db);
		}
	}
	
	public Cursor query(String sTableName,String[] sColums, String sWhereClause,
			String[] selectionArgs, String groupBy, String having,
			String orderBy, String limit) {
		Cursor c = null;
		try {
			// SQLiteDatabase db = getReadableDatabase();
			c = m_db.query(sTableName, sColums, sWhereClause, selectionArgs,
					groupBy, having, orderBy, limit);
		} catch (SQLiteException e) {
		}
		return c;
	}

	/*
	 * Returns:
	 * the row ID of the newly inserted row, or -1 if an error occurred , or RET_RECORD_EXIST if the record was exist
	 * */
	private long insert(String sTableName,ContentValues values) {
		try {
			//SQLiteDatabase db = getWritableDatabase();
			return m_db.insertOrThrow(sTableName, null, values);
		} catch (SQLiteException e) {
			LogUtil.e(this, "Could not insert the reocrd to database");
		}
		return -1;
	}
	
	/*
	 * Returns:
	 * the number of rows affected if a whereClause is passed in, 0 otherwise. To remove all rows and get a count pass "1" as the whereClause.
	 * -1 if an error occurred 
	 * */
	private int delete(String sTableName,String sWhereClause){
		try {
			//SQLiteDatabase db = getWritableDatabase();
			return m_db.delete(sTableName, sWhereClause, null);
		} catch (SQLiteException e) {
			LogUtil.e(this,"Could not delete record from database");
		}
		return -1;
	}
	
	/*
	 * Returns:
	 * the number of rows affected . -1 if an error occurred
	 * */
	private int update(String sTableName,String sWhereClause,ContentValues values) {
		try {
			//SQLiteDatabase db = getWritableDatabase();
			return m_db.update(sTableName, values, sWhereClause, null);
		} catch (SQLiteException e) {
			LogUtil.e(this,"Could not udpate record from database");
		}
		return -1;
	}

	
	private boolean isExist(String sTableName,String sWhereClause){
		Cursor c = null;
		boolean b = false;
		try {
			//SQLiteDatabase db = getReadableDatabase();
			LogUtil.e(this,"isExist->Table Name:" + sTableName + "     clause:" + sWhereClause);
			c = m_db.query(sTableName, new String[]{FIELD_ID}, sWhereClause, null, null,null, null, null);
			if (c != null) {
				LogUtil.e(this,"query was success and count is:" + c.getCount());
				b = c.getCount() != 0;
			}
		} catch (SQLiteException e) {
		} finally {
			if (c != null) {
				c.close();
			}
		}
		return b;
	}


	
	public boolean isExistProduct(String sWhereClause)
	{
		return isExist(TABLE_USER,sWhereClause);
	}
	
	
	public long addUser(String uid, String name, String access_token, String access_token_secret, String type)
	{
		if (access_token != null && !access_token.equals("") && access_token_secret != null && !access_token_secret.equals(""))
		{
			ContentValues values = new ContentValues();
			values.put(USER_ID,uid);
			values.put(USER_NAME,name);
			values.put(USER_ACCESS_TOKEN,access_token);
			values.put(USER_ACCESS_TOKEN_SECRET,access_token_secret);
			values.put(USER_TYPE,type);
			return insert(TABLE_USER,values);
		}
		else
		{
			return RET_INVALID_PARAMETER;
		}			
	}		
	
	public void updateById(String tableName,String id,ContentValues cv)
	{
		m_db.update(tableName, cv, "id = ?", new String[]{id});
	}

/*	public long insertProduct(MyListItem product) {
		if (product != null){
			ContentValues values = new ContentValues();
			values.put(FIELD_PRODUCT_SKU,product.Sku);
			values.put(FIELD_PRODUCT_NAME,product.ProductName);
			values.put(FIELD_IMAGE_LOCAL,product.ImageData);
			values.put(FIELD_IMAGE_URL_HTTP,product.ServerImagePath);
			values.put(FIELD_PRICE_RETIAL,product.RetailPrice);
			values.put(FIELD_ECOUPON_DESC ,product.EcouponDesc);
			values.put(FIELD_ECOUPON_ACTIVE,product.EcouponActive);
			values.put(FIELD_ECOUPON_CODE,product.ECouponCode);
			values.put(FIELD_ECOUPON_USED,product.EcouponHadUsed);
			values.put(FIELD_ECOUPON_AMOUNT,product.EcouponAmount);
			values.put(FIELD_DETAIL_TITLE,product.EcouponOfferDetailTitle);
			values.put(FIELD_DETAIL_SUB_TITLE,product.EcouponOfferDetailSubTitle);
			values.put(FIELD_DETAIL_DESC,product.EcouponOfferDetailDescription);
			values.put(FIELD_END_DATE,product.EndDate);
			values.put(FIELD_PERSONAL,product.HasPersonalization);
			values.put(FIELD_CATELOG_ID,product.CatalogId);
			return insert(TABLE_PRODUCT,values);
		} else {
			return RET_INVALID_PARAMETER;
		}
	}
	
	public int deleteProduct(String sWhereClause) {
		return delete(TABLE_PRODUCT,sWhereClause);
	}

	public int updateProduct(String sWhereClause,ContentValues sValues) {
		//ContentValues values = new ContentValues();
		//values.put(FIELD_CLASS, sNewClass);
		return update(TABLE_PRODUCT,sWhereClause,sValues);
	}



	private void fillFields(MyListItem product,Cursor c){

		int index = -1;
		
		index = c.getColumnIndex(FIELD_PRODUCT_SKU);
		if (index>= 0)
			product.Sku = c.getString(index);
		
		index = c.getColumnIndex(FIELD_PRODUCT_NAME);
		if (index>= 0)
			product.ProductName = c.getString(index);
		
		index = c.getColumnIndex(FIELD_IMAGE_LOCAL);
		if (index>= 0)
			product.ImageData = c.getString(index);

		index = c.getColumnIndex(FIELD_IMAGE_URL_HTTP);
		if (index>= 0)
			product.ServerImagePath = c.getString(index);
		

		index = c.getColumnIndex(FIELD_PRICE_RETIAL);
		if (index>= 0)
			product.RetailPrice = c.getString(index);
		
		index = c.getColumnIndex(FIELD_ECOUPON_DESC);
		if (index>= 0)
			product.EcouponDesc = c.getString(index);
		
		index = c.getColumnIndex(FIELD_ECOUPON_ACTIVE);
		if (index>= 0)
			product.EcouponActive = c.getString(index);
		
		index = c.getColumnIndex(FIELD_ECOUPON_CODE);
		if (index>= 0)
			product.ECouponCode = c.getString(index);
		
		index = c.getColumnIndex(FIELD_ECOUPON_USED);
		if (index>= 0)
			product.EcouponHadUsed = c.getString(index);
		
		index = c.getColumnIndex(FIELD_ECOUPON_AMOUNT);
		if (index>= 0)
			product.EcouponAmount = c.getString(index);
		
		index = c.getColumnIndex(FIELD_DETAIL_TITLE);
		if (index>= 0)
			product.EcouponOfferDetailTitle = c.getString(index);
		
		index = c.getColumnIndex(FIELD_DETAIL_SUB_TITLE);
		if (index>= 0)
			product.EcouponOfferDetailSubTitle = c.getString(index);
		
		index = c.getColumnIndex(FIELD_DETAIL_DESC);
		if (index>= 0)
			product.EcouponOfferDetailDescription = c.getString(index);
		
		index = c.getColumnIndex(FIELD_END_DATE);
		if (index>= 0)
			product.EndDate = c.getString(index);
		
		index = c.getColumnIndex(FIELD_PERSONAL);
		if (index>= 0)
			product.HasPersonalization = c.getString(index);
		
		index = c.getColumnIndex(FIELD_CATELOG_ID);
		if (index>= 0)
			product.CatalogId = c.getString(index);
		
	}

	
	public ArrayList<MyListItem> getRecords(String[] sColums, String sWhereClause,
			String[] selectionArgs, String groupBy, String having,
			String orderBy, String limit) {
		ArrayList<MyListItem> result = null;
		Cursor c = null;
		try {
			//SQLiteDatabase db = getReadableDatabase();
			c = m_db.query(TABLE_PRODUCT, sColums, sWhereClause,
					selectionArgs, groupBy, having, orderBy, limit);
			if (c != null) {
				result = new ArrayList<MyListItem>(c.getCount());
				for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()) {
					MyListItem record = new MyListItem();
					fillFields(record,c);
					result.add(record);
				}
			}
		} catch (SQLiteException e) {
			Log.e(TAG,"Could not load data from database", e);
		} finally {
			if (c != null) {
				c.close();
			}
		}
		return result;
	}*/
}